/*
 * DataClient.c
 *
 *  Created on: 2013. 4. 14.
 *      Author: tj-np2
 */


#include	"unp.h"

int
main(int argc, char **argv)
{
	int					sockfd, n;
	char				recvline[MAXLINE + 1];
	char				fileNameBuf[MAXLINE + 1];
	struct sockaddr_in	servaddr;
	char c;
	FILE *fp, *fp1;
	char fileName;

	if (argc != 4)
			err_quit("Usage: DataClient <IPAddress> <PortNumber> <FileName>");

		sockfd = Socket(AF_INET, SOCK_STREAM, 0);

		bzero(&servaddr, sizeof(servaddr));
		servaddr.sin_family = AF_INET;
		servaddr.sin_port = htons(atoi(argv[2]));
		Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
		err_sys("connect error");

	strcpy(fileNameBuf, argv[3]);
	Write(sockfd, fileNameBuf, sizeof(fileNameBuf));

	if((fp1 = fopen("Output.txt", "w")) == NULL)
	{
		printf("Output 파일을 생성하지 못했습니다.");
		return 0;
	}

	while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {

		recvline[n] = 0;	/* null terminate */

		if (fputs(recvline, fp1) == EOF) {
			err_sys("fputs error");
		}

		if (n < 0)
				err_sys("read error1");
	}

	printf("Server로부터 수신을 완료했습니다.\n");
	fclose(fp1);
	exit(0);
}
